package com.example.villagemanager.network;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.io.File;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Greenhouse
 * Created by zhoudan on 2018/1/25.
 * RetrofitHelper
 * Version 1.0
 * CopyRight 麦卡
 */

public class RetrofitHelper {

    private static final int HTTP_RESPONSE_DISK_CACHE_MAX_SIZE = 10 * 1024 * 1024;//缓存最大大小
    public static final int TIMEOUT_READ = 15;//读取超时
    public static final int TIMEOUT_CONNECTION = 10;//连接超时
    public static final int TIMEOUT_WRITE = 20;
    private static Retrofit retrofit;

    public static <T> T create(Class<T> clazz) {
        return retrofit.create(clazz);
    }

    public static void init(Context context){
        GsonBuilder builder = new GsonBuilder();
        // Register an adapter to manage the date types as long values
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        });
        Gson gson = builder.create();
        if (retrofit == null) {
            synchronized (RetrofitHelper.class) {

                retrofit = new Retrofit.Builder()
                        // 设置OKHttpClient
                        .client(getOkHttpClient(context))
                        // String转换器，防止提交的参数带引号
                        .addConverterFactory(ScalarsConverterFactory.create())
                        // gson转化器
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        // RxJava
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .baseUrl(UrlDefine.BASE_URL)
                        .build();
            }
        }
    }

    /**
     * httpClient
     *
     * @param context
     * @return
     */
    private static OkHttpClient getOkHttpClient(Context context) {
        //拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        // 设置缓存路径
        File baseDir = context.getCacheDir();
        File cacheDir = new File(baseDir, "HttpResponseCache");
        // 设置缓存 10M
        Cache cache = new Cache(cacheDir, HTTP_RESPONSE_DISK_CACHE_MAX_SIZE);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                // 打印日志
                .addInterceptor(loggingInterceptor)

                // 设置Cache目录
                .cache(cache)

                /*
                 * //设置缓存 .addInterceptor(cacheInterceptor)
                 * .addNetworkInterceptor(cacheInterceptor)
                 */
                // 失败重连
                .retryOnConnectionFailure(true)

                // time out
                .readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)
                .connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT_WRITE, TimeUnit.SECONDS)
                .build();
        return okHttpClient;
    }
}
